package com.sprocomm.agingtest.camera;

import com.sprocomm.agingtest.R;
import com.sprocomm.agingtest.Tools;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import java.io.File;

@SuppressWarnings("MissingPermission")
public class VideoTest2 extends AppCompatActivity {
    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private CameraManager mCameraManager;

    private CameraDevice.StateCallback mStateCallback;
    private Handler mHandler;
    private HandlerThread mThreadHandler;
    private CaptureRequest.Builder mPreviewBuilder;
    private MediaRecorder mMediaRecorder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_test);
        //动态权限申请
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.RECORD_AUDIO}, 0x001);
            return;
        }
        mMediaRecorder = new MediaRecorder();
        mThreadHandler = new HandlerThread("VideoTest2");
        mThreadHandler.start();
        mHandler = new Handler(mThreadHandler.getLooper());

        mSurfaceView = (SurfaceView) findViewById(R.id.sv_preview);
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mStateCallback = new CameraDevice.StateCallback() {
            @Override
            public void onOpened(CameraDevice camera) {
                Tools.logE("onOpened");
                try {
                    startPreview(camera);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onDisconnected(CameraDevice camera) {
                Log.e("Vedio2","onDisconnected");
            }

            @Override
            public void onError(CameraDevice camera, int error) {
                Log.e("Vedio2","onError");
            }
        };

        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Log.e("Vedio2","surfaceCreated");
                mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
                try {
                    mCameraManager.openCamera("0",mStateCallback,mHandler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.e("Vedio2","surfaceChanged");
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                Log.e("Vedio2","surfaceDestroyed");
            }
        });
    }

    private void startPreview(CameraDevice camera) throws CameraAccessException {
//        SurfaceTexture texture = mPreviewView.getSurfaceTexture();
//        texture.setDefaultBufferSize(mPreviewView.getWidth(), mPreviewView.getHeight());
//        Surface surface = new Surface(texture);
        //mSurfaceHolder.setFixedSize(mSurfaceView.getWidth(),mSurfaceView.getHeight());
        Surface surface = mSurfaceHolder.getSurface();
        if(surface == null){
            Log.e("Vedio2","surface is null");
        }
        setMediaRecorder(surface);
        try {
            mPreviewBuilder = camera.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        mPreviewBuilder.addTarget(surface);
        //camera.createCaptureSession(Arrays.asList(surface), mSessionStateCallback, mHandler);
    }
    private File getFilePath() {
        File root = Environment.getExternalStorageDirectory();
        File file = new File(root.getAbsolutePath() + "/AgingTest/Temp");
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    public void setMediaRecorder(Surface surface) {
        // Set audio and video source and encoder
        // 这两项需要放在setOutputFormat之前
        try {
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

            // Set output file format
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

            // 这两项需要放在setOutputFormat之后
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);

            mMediaRecorder.setVideoSize(320, 240);
            mMediaRecorder.setVideoFrameRate(20);
            mMediaRecorder.setPreviewDisplay(surface);
            mMediaRecorder.setOrientationHint(90);
            mMediaRecorder.setOutputFile(File.createTempFile("Vedio", ".3gp", getFilePath()).getAbsolutePath());


            mMediaRecorder.prepare();
            mMediaRecorder.start();
            Log.d("VIdeo2", "bf mRecorder.prepare()");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d("VIdeo2", "bf mRecorder.start()");
    }
    public void start(View view) {
        mMediaRecorder.stop();
        mMediaRecorder.reset();
    }
}
